#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mythread.h"
#include <QPushButton>
#include <QThread>
// renew

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 主线程
    // 1. 创建子线程对象
    QThread* t1 = new QThread;
    QThread* t2 = new QThread;
    QThread* t3 = new QThread;

    // 2. 创建任务类对象
    Generate *gen = new Generate;
    QuickSort* quick = new QuickSort;
    BubbleSort* bubble = new BubbleSort;

    // 3. 将任务对象移动到子线程中
    gen->moveToThread(t1);
    bubble->moveToThread(t2);
    quick->moveToThread(t3);

    // 检测父线程发出的starting信号，并接收
    connect(this, &MainWindow::starting, gen, &Generate::working);
    // 2. 启动子线程
    connect(ui->start, &QPushButton::clicked, this, [=]()
    {
        emit starting(10000); // 启动并传递给子线程 参数
        t1->start();
    });

    connect(gen, &Generate::sendVector, bubble, &BubbleSort::working);
    connect(gen, &Generate::sendVector, quick, &QuickSort::working);
    // 3. 接收子线程传递的num
    connect(gen, &Generate::sendVector, this, [=](QVector<int> qv)
    {
        t2->start();
        t3->start();

        // 将获取到的随机数插入到随机数列表框中
        for(int i = 0; i < qv.size(); ++i)
        {
            ui->RandList->addItem(QString::number(qv.at(i)));
        }
    });

    connect(bubble, &BubbleSort::finish, this, [=](QVector<int> qv)
    {
        for(int i = 0; i < qv.size(); ++i)
        {
            ui->bubbleList->addItem(QString::number(qv.at(i)));
        }
    });
    connect(quick, &QuickSort::finish, this, [=](QVector<int> qv)
    {
        for(int i = 0; i < qv.size(); ++i)
        {
            ui->quickList->addItem(QString::number(qv.at(i)));
        }
    });


    // 释放资源
    connect(this, &MainWindow::destroyed, this, [=]()
    {
        t1->quit();
        t1->wait();
        t1->deleteLater(); // 等价于 delete t1

        // ...t2
        // ...t3

        gen->deleteLater();
        bubble->deleteLater();
        quick->deleteLater();
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

